using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;

//  让一个UI飞到另外一个地方，类似飞金币,依赖Dotween

public class UIJumpComponent : BaseComponent
{
    /// <summary>
    /// UI飞到指定位置，targetPos为目标位置，duration为持续时间，ease为缓动类型
    /// </summary>
    /// <param name="rectTransform">Canvas</param>
    /// <param name="targetPos">目标位置</param>
    /// <param name="CompleteEvent">完成时间</param>
    /// <param name="UpdateEvent">动画执行中每帧执行的事件</param>
    /// <param name="duration">动画持续事件</param>
    /// <param name="ease">动画缓动效果</param>
    public void UIJump(RectTransform rectTransform,Vector2 targetPos,Action CompleteEvent = null,Action UpdateEvent = null,float duration= 0.5f,Ease ease = Ease.Linear)
    {
        rectTransform.DOAnchorPos(targetPos, duration).SetEase(ease).OnComplete(() =>
        {
            CompleteEvent?.Invoke();
        }).OnUpdate(() =>
        {
            UpdateEvent?.Invoke();
        });
    }

    public void UIJump(RectTransform rectTransform,Vector3 targetpos,Action CompleteEvent,Action UpdateEvent = null,float duration= 0.5f,Ease ease = Ease.Linear)
    {
        Vector2 pos = UpdateRectPosition(rectTransform.parent.GetComponent<RectTransform>(),targetpos,Vector2.zero); //获取targetpos在指定本地坐标下的坐标

        rectTransform.DOAnchorPos(pos,duration).SetEase(ease).OnComplete(() =>
        {
            CompleteEvent?.Invoke();
        }).OnUpdate(() =>
        {
            UpdateEvent?.Invoke();
        });
    }

    private Vector2 UpdateRectPosition(RectTransform LocalRectangle,Vector3 EnemyTransform,Vector2 Offset)
    {
        Vector3 MyWorldPosition =EnemyTransform;
        Vector2 screenPosition = Camera.main.WorldToScreenPoint(MyWorldPosition); //世界坐标转屏幕坐标
        Vector2 localPosition;
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle(LocalRectangle,screenPosition,null,out localPosition))  //屏幕坐标转对应Rect下的本地坐标
        {
            return localPosition + Offset;
        }
        return Vector2.zero;
    }
}
